﻿import type { RequestOptions } from '@@/plugin-request/request';
import type { RequestConfig } from '@umijs/max';
import { message } from 'antd';
import { history } from 'umi';
import AdminConfig from './config/baseConfig';
import { ErrorShowType, ResponseStructure } from './model/responseModel';

export const errorConfig: RequestConfig = {
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
  },
  baseURL:
    process.env.NODE_ENV === 'production' ? AdminConfig.Pro_API_URL : AdminConfig.Dev_API_URL, // 默认的API地址,
  errorConfig: {
    // 错误抛出
    errorThrower: (res) => {
      const { success, result, errorCode, errorMessage } =
        res as unknown as ResponseStructure<null>;
      if (!success) {
        const error: any = new Error(errorMessage);
        error.name = 'BizError';
        error.info = { errorCode, errorMessage, result };
        throw error; // 抛出自制的错误
      }
    },
    // 错误接收及处理
    errorHandler: (error: any, opts: any) => {
      if (opts?.skipErrorHandler) throw error;
      // 我们的 errorThrower 抛出的错误。
      if (error.name === 'BizError') {
        const errorInfo: ResponseStructure<null> | undefined = error.info;
        if (errorInfo) {
          const { errorMessage } = errorInfo;
          switch (errorInfo.errorCode) {
            case ErrorShowType.ERROR_MESSAGE:
              message.error(errorMessage);
              break;
            default:
              message.error(errorMessage);
          }
        }
      } else if (error.response) {
        switch (error.response.status) {
          case 401:
            window.location.href = '/user/login';
            break;
          case 403:
            message.error('没有访问权限,请联系管理员!');
            break;
          case 500:
            message.error('服务器错误!');
            break;
          default:
            message.error(`返回异常:${error.response.status},请联系管理员!`);
            break;
        }
      } else if (error.request) {
        message.error('服务器无反应,请重试!');
      } else {
        message.error('请求异常,请重试!');
      }
    },
  },

  // 请求拦截器
  requestInterceptors: [
    (config: RequestOptions) => {
      const token = localStorage.getItem(AdminConfig.TOKEN_KEY) as string;
      if (token) {
        config.headers = {
          ...config.headers,
          'X-Token': `${token}`,
        };
        return { ...config };
      } else {
        history.push('/user/login');
      }
      return { ...config };
    },
  ],

  // 响应拦截器
  responseInterceptors: [
    (response) => {
      if (response.status === 401) {
        console.log('你未登录');
        history.push('/user/login');
      } else {
        if (response.headers['new-token']) {
          localStorage.setItem(AdminConfig.TOKEN_KEY, response.headers['new-token']);
        }
      }
      const { success, errorMessage } = response.data as unknown as ResponseStructure<null>;
      if (!success) {
        message.error(errorMessage);
      }
      return response;
    },
  ],
};
